package com.mlearning.demo.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    //标示符：表示当前用户未登录(可根据自己项目需要改为json样式)
    String NO_LOGIN = "您还未登录";
    //不需要登录就可以访问的路径(比如:注册登录等)
    String[] includeUrls = new String[]{"/login", "/register", "/", "/API/books", "/show","/API/graph","/book",
            "/checkusername","/checkcode","/checkuseremail","/SendEmailServlet","/API/book_detail","/book_detail"};
    String[] includeEndWith = new String[]{".js",".css",".png",".ico",".xml",".json",".svg",".jpg",".gif",".map",".woff",
    ".ttf",".woff2"};
    String[] needFilter = new String[]{"/personal_center","/recommend","/addMybook"};

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession(false);
        String uri = request.getRequestURI();
//        if (request.isRequestedSessionIdFromURL()) {
//            if (null != session) {
//                session.invalidate();
//            }
//        }
        //是否需要过滤
        boolean needFilter = isNeedFilter(uri);

        if (!needFilter) { //不需要过滤直接传给下一个过滤器
            chain.doFilter(req, resp);
        } else {//需要过滤器
            System.out.println("filter url:" + uri);
            // session中包含user对象,则是登录状态
            if (session != null && session.getAttribute("user") != null) {
//             System.out.println("user:"+session.getAttribute("user"));
                chain.doFilter(request, response);
            } else {
                String requestType = request.getHeader("X-Requested-With");
                //判断是否是ajax请求
                if (requestType != null && "XMLHttpRequest".equals(requestType)) {
                    response.getWriter().write(this.NO_LOGIN);

                } else {
                    //重定向到登录页(需要在static文件夹下建立此html文件)
                    System.out.println("root_url:" + request.getContextPath());
                    response.sendRedirect(request.getContextPath() + "/login");
//                    return "login/login";
                }
            }
        }


    }

    /**
     * @param uri
     * @Author: xxxxx
     * @Description: 是否需要过滤
     * @Date: 2018-03-12 13:20:54
     */
    public boolean isNeedFilter(String uri) {
        for (String includeEnd : includeEndWith){
            if(uri.endsWith(includeEnd)){
                return false;
            }
            if(uri.contains(includeEnd)){
                return false;
            }
        }
        for (String includeUrl : includeUrls) {
            if (includeUrl.equals(uri)) {
                return false;
            }
//            if (uri.contains(includeUrl)){
//                return false;
//            }
        }
        return true;
    }
    public void init(FilterConfig config) throws ServletException {

    }

}
